<script lang="ts" setup>
import type { ColumnsType } from 'ant-design-vue/es/table'
import type { RequestTableData } from '../request-table/typing'
import type { FilterItem } from '~@/components/search-filter/typing'
import RequestTable from '~@/components/request-table/index.vue'
import SearchFilter from '~@/components/search-filter/index.vue'

const props = defineProps<{
  request: (params: any) => Promise<any>
  columns: ColumnsType<any>
  searchColumns: FilterItem[]
  showIndex?: boolean
  immediate?: boolean
  labelWidth?: number
  maxRow?: number
}>()

const emit = defineEmits<{
  (e: 'success', res: any): void
  (e: 'error', err: any): void
  (e: 'searchChange', params: any): void
}>()

const queryParams = ref({})

const handleSearch = function (values: Record<string, any>) {
  queryParams.value = values
  emit('searchChange', values)
}
const handleReset = function () {
  queryParams.value = {}
  emit('searchChange', {})
}

const getListApi = function (data: any): Promise<RequestTableData<any>> {
  return new Promise((resolve) => {
    props.request(data)
      .then((res) => {
        emit('success', res)
        resolve(res)
      })
      .catch((err) => {
        emit('error', err)
        const emptyData: RequestTableData<any> = {
          list: [],
          total: 0,
          page: 0,
          limit: 0,
        }
        resolve(emptyData)
      })
  })
}

const RequestTableWithType = RequestTable<any>
</script>

<template>
  <div>
    <SearchFilter
      :filters="searchColumns" :label-width="labelWidth" :max-row="maxRow" @search="handleSearch"
      @reset="handleReset"
    />
    <RequestTableWithType
      :request="getListApi" :columns="columns" :params="queryParams" :show-index="showIndex"
      :immediate="immediate" @success="emit('success', $event)"
    >
      <template v-for="(_, name) in $slots" #[name]="slotData">
        <slot :name="name" v-bind="slotData" />
      </template>
    </RequestTableWithType>
  </div>
</template>
